<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      title="编辑昵称"
      left-text="取消"
      right-text="保存"
      @click-left="$emit('close')"
      @click-right="onSave"
    />
    <!-- 输入框 -->
    <van-field
      v-model="name"
      type="input"
      maxlength="7"
      placeholder="请输入新昵称"
      show-word-limit
    />
  </div>
</template>

<script>
import { editUserProfile } from '@/api/user.js'
export default {
  data () {
    return {
      name: this.value
    }
  },
  props: {
    value: {
      type: String,
      required: true
    }
  },
  created () {

  },
  methods: {
    // 点击修改昵称
    async onSave () {
      if (this.name.trim === '') {
        this.$toast.success('昵称不能为空')
      }
      try {
        await editUserProfile({ name: this.name })
        this.$toast.success('修改昵称成功')
        this.$emit('close')
        this.$emit('input', this.name)
        this.name = ''
      } catch (err) {
        if (err.response && err.response.status === 409) {
          return this.$toast.success('用户名已存在')
        }
        this.$toast.success('修改失败,请稍后再试')
      }
    }
  }
}
</script>

<style scoped lang='less'>
/deep/ .van-nav-bar__text {
  color: #fff !important;
}
</style>
